import projectApi from '@/api/project'
import { Button, Input, message, Tree } from 'antd'
import { DataNode } from 'antd/lib/tree'
import React, { useEffect, useState } from 'react'
export default function RoleAuth(props: any) {
  const { search } = props.location
  let query = search.split('&')
  let id = query[0].slice(query[0].indexOf('=') + 1)
  let roleName = query[1].slice(query[1].indexOf('=') + 1)
  const [treeList, setTreeList] = useState([])
  const [selectTree, setSeletTree] = useState<string[]>([])
  const [flag, setFlag] = useState(false)
  const [treeSelecet, setTreeSelect] = useState<string[]>([])
  const reqTreeList = async () => {
    try {
      let result = await projectApi.reqTreeList(id)
      setTreeList(result.children)
      selectTreeList(result.children)
      setFlag(true)
      return Promise.resolve('成功')
    } catch (error) {
      return Promise.reject('')
    } finally {
    }
  }
  useEffect(() => {
    reqTreeList()
  }, [])
  // 默认选中
  const selectTreeList = (treeList: any[]) => {
    treeList.forEach((item) => {
      if (item.children) selectTreeList(item.children)
      if (item.select && item.type == 2) {
        selectTree.push(item.id)
        treeSelecet.push(item.id)
      }
    })
  }
  const treeCheck = (selectTree: any) => {
    setTreeSelect([...selectTree])
  }
  const saveSelectTree = async () => {
    try {
      await projectApi.saveAssign(id, treeSelecet)
      message.success('保存成功')
      props.history.push(`/acl/role/list`)
    } catch (error) {
      message.error(error)
    }
  }
  return (
    <>
      <Input style={{ marginBottom: 20 }} disabled value={roleName} />
      {flag && (
        <Tree
          checkable
          treeData={treeList}
          defaultCheckedKeys={selectTree}
          defaultExpandedKeys={selectTree}
          fieldNames={{ children: 'children', key: 'id', title: 'name' }}
          onCheck={treeCheck}
        />
      )}
      <Button style={{ marginRight: 10 }} type="primary" onClick={saveSelectTree}>
        保存
      </Button>
      <Button
        onClick={() => {
          props.history.push(`/acl/role/list`)
        }}
      >
        取消
      </Button>
    </>
  )
}
